BRANCHING IN JAVASCRIPT
This note explains branching in simple language.
Branching is one of the most important ideas in programming, because it allows a program to make decisions.
A program often needs to answer questions like:
- Is the user an adult?
- Is the password correct?
- Is there enough product in stock?
- Which subscription plan did the user choose?
When the answer changes, the program must do different things. That is exactly what branching is for.
1. What is branching?
Branching means choosing different paths in code depending on a condition.
Example from real life:
- if a user has a pro subscription, unlimited download
- if a user has a free subscription, limited download
So:
- the condition is the subscription type
- the branch is what action the program takes next
Diagram 1. Basic idea of branching
Start
↓
Check condition
↓
true → go to branch A
false → go to branch B
Explanation
A branching statement checks a condition and then chooses one path.
That condition usually becomes:
true- or
false
2. Why branching is important
Without branching, a program would always do the same thing.
With branching, a program can react to different situations.
Examples:
- show one message for adults and another for children
- approve or reject an order
- return one price for one plan and another price for another plan
- allow or deny access
Diagram 2. Real-life branching examples
Condition: age >= 18
true → adult
false → not adult
Condition: password is correct
true → access granted
false → access denied
Explanation
Branching is the basis of smart program behavior.
3. The if statement
The if statement runs code only if a condition is true.
Syntax
if (condition) {
// code runs if condition is true
}
Important idea
JavaScript checks the condition inside the parentheses.
- if the condition is
true, code inside{}runs - if the condition is
false, code inside{}is skipped
Diagram 3. How if works
if (condition) {
code
}
1. Check condition
2. If true → run code
3. If false → skip code
Explanation
if is the simplest form of branching.
4. Example of if
let price = 0;
const subscription = "pro";
if (subscription === "pro") {
price = 100;
}
console.log(price); // 100
What happens here?
pricestarts as0- JavaScript checks:
subscription === "pro" - this is
true - so
price = 100
Diagram 4. if with subscription = "pro"
price = 0
subscription = "pro"
Check:
subscription === "pro"
↓
true
↓
price = 100
Explanation
Because the condition is true, the code inside the if block runs.
5. Example when if condition is false
let price = 0;
const subscription = "free";
if (subscription === "pro") {
price = 100;
}
console.log(price); // 0
What happens here?
pricestarts as0- JavaScript checks:
subscription === "pro" - this is
false - the
ifblock is skipped pricestays0
Diagram 5. if with subscription = "free"
price = 0
subscription = "free"
Check:
subscription === "pro"
↓
false
↓
skip if block
↓
price stays 0
Explanation
If the condition is false, JavaScript simply jumps over the block.
6. Function example with if
function getPrice(subscription) {
let price = 0;
if (subscription === "pro") {
price = 100;
}
return price;
}
console.log(getPrice("free")); // 0
console.log(getPrice("pro")); // 100
Diagram 6. How getPrice() works
Call: getPrice("free")
1. price = 0
2. check "free" === "pro" → false
3. do not change price
4. return 0
Call: getPrice("pro")
1. price = 0
2. check "pro" === "pro" → true
3. price = 100
4. return 100
Explanation
The function starts with a default value and changes it only when the condition is true.
7. checkAge(age) with if
Task idea:
Return "You are an adult" only if age >= 18.
Correct version
function checkAge(age) {
if (age >= 18) {
return "You are an adult";
}
}
console.log(checkAge(20)); // "You are an adult"
console.log(checkAge(17)); // undefined
console.log(checkAge(10)); // undefined
console.log(checkAge(30)); // "You are an adult"
Important note
For ages below 18, this function returns undefined, not the string "undefined".
That is an important difference.
Diagram 7. How checkAge(age) works
age >= 18 ?
│
├─ true → return "You are an adult"
└─ false → return undefined
Explanation
There is no else here. So if the condition is false, JavaScript reaches the end of the function and returns undefined.
8. The if...else statement
Sometimes you need two branches:
- one branch if the condition is true
- another branch if the condition is false
That is what if...else is for.
Syntax
if (condition) {
// code if true
} else {
// code if false
}
Diagram 8. How if...else works
Check condition
│
├─ true → run if block
└─ false → run else block
Explanation
if...else always chooses exactly one of two branches.
9. Example of if...else
const grade = 85;
if (grade >= 70) {
console.log("Satisfactory");
} else {
console.log("Unsatisfactory");
}
Since 85 >= 70 is true, the output is:
Satisfactory
Diagram 9. Grade check with if...else
grade = 85
Check:
grade >= 70
↓
true
↓
"Satisfactory"
Explanation
Only the if block runs. The else block is ignored.
10. Example when else runs
const grade = 40;
if (grade >= 70) {
console.log("Satisfactory");
} else {
console.log("Unsatisfactory");
}
Since 40 >= 70 is false, the output is:
Unsatisfactory
Diagram 10. Grade check when condition is false
grade = 40
Check:
grade >= 70
↓
false
↓
"Unsatisfactory"
Explanation
When the condition is false, JavaScript goes to the else branch.
11. Function example with if...else
function checkGrade(grade) {
if (grade >= 70) {
return "Satisfactory";
} else {
return "Unsatisfactory";
}
}
console.log(checkGrade(40)); // "Unsatisfactory"
console.log(checkGrade(75)); // "Satisfactory"
Diagram 11. How checkGrade() works
grade >= 70 ?
│
├─ true → return "Satisfactory"
└─ false → return "Unsatisfactory"
Explanation
This function always returns one of two strings.
12. checkStorage(available, ordered) with if...else
Task idea:
- if ordered amount is greater than stock, not enough goods
- otherwise, order is processed
Correct version
function checkStorage(available, ordered) {
if (ordered > available) {
return "Not enough goods in stock!";
} else {
return "Order is processed, our manager will contact you";
}
}
console.log(checkStorage(100, 50));
console.log(checkStorage(100, 130));
console.log(checkStorage(200, 20));
console.log(checkStorage(200, 150));
console.log(checkStorage(150, 180));
Important note
The correct condition is:
ordered > available
Not available <= ordered, because equal values like 80, 80 should still be accepted in the later task example.
Diagram 12. How checkStorage() works
ordered > available ?
│
├─ true → "Not enough goods in stock!"
└─ false → "Order is processed, our manager will contact you"
Explanation
If ordered quantity is bigger than stock, the order cannot be completed.
If it is equal to or smaller than stock, the order is accepted.
13. The else if block
Sometimes two branches are not enough.
You may need to check several conditions in order.
For this, JavaScript uses:
ifelse ifelse
Syntax
if (condition1) {
// code
} else if (condition2) {
// code
} else if (condition3) {
// code
} else {
// code
}
Diagram 13. How else if chain works
Check condition 1
│
├─ true → run block 1 and stop
└─ false → check condition 2
│
├─ true → run block 2 and stop
└─ false → check condition 3
│
├─ true → run block 3 and stop
└─ false → run else block
Explanation
JavaScript checks conditions from top to bottom. It stops at the first true condition.
That is very important.
14. Example of else if
function checkGrade(grade) {
if (grade >= 90) {
return "Perfectly";
} else if (grade >= 80) {
return "Good";
} else if (grade >= 70) {
return "Satisfactory";
} else {
return "Unsatisfactory";
}
}
console.log(checkGrade(85));
Output:
Good
Why?
85 >= 90, false85 >= 80, true- so JavaScript returns
"Good"and stops - it does not check the remaining branches
Diagram 14. else if stops at first true condition
grade = 85
1. grade >= 90 → false
2. grade >= 80 → true → run this block
3. stop
Explanation
Even though 85 >= 70 is also true, JavaScript never reaches that branch because it already found the first true one.
15. checkStorage(available, ordered) with else if
Now the task has three branches:
- no products in the order
- ordered quantity is too large
- otherwise the order is accepted
Correct version
function checkStorage(available, ordered) {
if (ordered === 0) {
return "There are no products in the order!";
} else if (ordered > available) {
return "Your order is too large, there are not enough items in stock!";
} else {
return "The order is accepted, our manager will contact you";
}
}
console.log(checkStorage(100, 50));
console.log(checkStorage(100, 130));
console.log(checkStorage(70, 0));
console.log(checkStorage(200, 20));
console.log(checkStorage(200, 250));
console.log(checkStorage(150, 0));
console.log(checkStorage(80, 80));
Diagram 15. Full storage decision chain
ordered === 0 ?
│
├─ yes → "There are no products in the order!"
└─ no
↓
ordered > available ?
│
├─ yes → "Your order is too large, there are not enough items in stock!"
└─ no → "The order is accepted, our manager will contact you"
Explanation
This is a good example of when else if is useful, because there are more than two possible situations.
16. Ternary operator
The ternary operator is a short version of if...else.
Syntax
condition ? valueIfTrue : valueIfFalse
How it works
- JavaScript checks the condition
- if true, result after
? - if false, result after
:
Diagram 16. Ternary operator flow
condition ? trueValue : falseValue
1. Check condition
2. If true → use trueValue
3. If false → use falseValue
Explanation
The ternary operator returns a value, so it is often used in assignment or return.
Example 1. Check age
let age = 20;
let message = age >= 18 ? "Adult" : "Not adult";
console.log(message);
Result:
Adult
Explanation
age >= 18 is true, so JavaScript uses "Adult".
Example 2. Check if number is positive
let number = 5;
let result = number > 0 ? "Positive number" : "Zero or negative number";
console.log(result);
Result:
Positive number
Example 3. Check password length
let password = "hello123";
let result = password.length >= 8 ? "Strong enough" : "Too short";
console.log(result);
Result:
Strong enough
Explanation
password.length means the number of characters in the password.
"hello123" has 8 characters.
So the condition password.length >= 8 is true.
Example 4. Check if user is logged in
let isLoggedIn = true;
let message = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(message);
Result:
Welcome back!
Explanation
isLoggedIn is already true or false.
So we do not need to write:
isLoggedIn === true
Example 5. Choose price with discount
let hasDiscount = false;
let price = hasDiscount ? 80 : 100;
console.log(price);
Result:
100
Explanation
hasDiscount is false, so JavaScript uses the value after :.
17. Example: adult or child
With if...else
let type;
const age = 20;
if (age >= 18) {
type = "adult";
} else {
type = "child";
}
console.log(type); // "adult"
With ternary operator
const age = 20;
const type = age >= 18 ? "adult" : "child";
console.log(type); // "adult"
Diagram 17. if...else vs ternary
if...else:
more lines, very clear
ternary:
shorter, good for simple choice
age >= 18 ? "adult" : "child"
Explanation
The ternary operator is best for short, simple two-branch choices.
18. Example: bigger of two numbers
With if...else
const a = 5;
const b = 10;
let biggerNumber;
if (a > b) {
biggerNumber = a;
} else {
biggerNumber = b;
}
console.log(biggerNumber); // 10
With ternary
const a = 5;
const b = 10;
const biggerNumber = a > b ? a : b;
console.log(biggerNumber); // 10
Diagram 18. Bigger number with ternary
a > b ?
│
├─ true → use a
└─ false → use b
Explanation
This is a classic case where the ternary operator is very convenient.
19. Function with ternary operator
function getBiggerNumber(a, b) {
return a > b ? a : b;
}
console.log(getBiggerNumber(5, 10)); // 10
console.log(getBiggerNumber(20, 15)); // 20
console.log(getBiggerNumber(7, 7)); // 7
Diagram 19. How getBiggerNumber() works
a > b ?
│
├─ true → return a
└─ false → return b
Explanation
If both numbers are equal, a > b is false, so the function returns b. In this case, b has the same value anyway.
20. checkPassword(password) with ternary
function checkPassword(password) {
const correctPassword = "jqueryismyjam";
return password === correctPassword
? "Access granted"
: "Access denied, wrong password!";
}
console.log(checkPassword("jqueryismyjam"));
console.log(checkPassword("angul4r1sl1f3"));
console.log(checkPassword("r3actsux"));
Diagram 20. Password check with ternary
password === correctPassword ?
│
├─ true → "Access granted"
└─ false → "Access denied, wrong password!"
Explanation
This is a good ternary example because there are exactly two possible results.
21. When to use ternary operator
The ternary operator is good when:
- the logic is short
- there are only two outcomes
- you want to assign or return a value
It is not good for long or complicated branching.
Diagram 21. When ternary is a good choice
Good for:
- two results
- short assignment
- short return
Bad for:
- many conditions
- long complex logic
Explanation
Readable code is more important than short code.
22. The switch statement
switch is useful when you compare one value with many exact possible values.
Syntax
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Diagram 22. How switch works
1. Evaluate expression
2. Compare it with each case
3. If match found → run that case
4. break stops switch
5. If no match → run default
Explanation
switch compares using strict equality (===).
So it is good for checking exact values like:
"starter""professional""organization"
It is not good for checks like:
age > 18score >= 70
23. Example of switch
const fruit = "apple";
switch (fruit) {
case "apple":
console.log("Apple selected");
break;
case "banana":
console.log("Banana selected");
break;
case "orange":
console.log("Orange selected");
break;
default:
console.log("The fruit is unknown");
}
Diagram 23. Fruit switch logic
fruit = "apple"
Compare with cases:
- "apple" → match
- run "Apple selected"
- break
- stop
Explanation
After a match is found, break stops the switch.
24. The break statement
break is used to exit the switch.
If break is missing, JavaScript continues into the next case. This is called fall-through.
Diagram 24. Why break matters
case match
↓
run case code
↓
break
↓
exit switch
Explanation
Without break, more case blocks may run by accident.
25. Fall-through example
const day = 3;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
console.log("This is a working day");
break;
case 6:
case 7:
console.log("It is a day off");
break;
default:
console.log("Invalid");
}
Diagram 25. Grouped cases in switch
day = 3
Matches:
case 3
↓
No code before shared block
↓
run:
"This is a working day"
↓
break
Explanation
Cases 1 to 5 share the same result. This is a useful and correct use of fall-through.
26. getSubscriptionPrice(type) with switch
function getSubscriptionPrice(type) {
switch (type) {
case "starter":
return 0;
case "professional":
return 20;
case "organization":
return 50;
default:
return "Invalid subscription type!";
}
}
console.log(getSubscriptionPrice("professional")); // 20
console.log(getSubscriptionPrice("organization")); // 50
console.log(getSubscriptionPrice("starter")); // 0
console.log(getSubscriptionPrice("random")); // "Invalid subscription type!"
Diagram 26. Subscription switch map
type
│
├─ "starter" → 0
├─ "professional" → 20
├─ "organization" → 50
└─ anything else → "Invalid subscription type!"
Explanation
This is a perfect use case for switch, because one value is compared against several exact text options.
27. Choosing between if, ternary, and switch
You now know several branching tools.
Use the right one for the right situation.
Give me some examples.
Here are examples for each branching tool.
1. if → one condition
Use if when you want to check one condition.
const age = 20;
if (age >= 18) {
console.log("You are an adult");
}
Explanation
If age is 18 or more, the code runs.
If not, nothing happens.
2. if...else → two branches
Use if...else when there are two possible results.
const isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in");
}
Explanation
If isLoggedIn is true, run the first block.
If isLoggedIn is false, run the else block.
3. else if → many different conditions
Use else if when you have many different conditions.
const score = 75;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 70) {
console.log("Good");
} else if (score >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
Explanation
JavaScript checks conditions from top to bottom.
When one condition is true, that block runs.
The other blocks are skipped.
4. Ternary → short two-result expression
Use ternary for a short if...else.
const age = 17;
const message = age >= 18 ? "Adult" : "Not adult";
console.log(message);
Explanation
If age >= 18 is true, message is "Adult".
If not, message is "Not adult".
5. switch → one value, many exact matches
Use switch when you compare one value with many exact options.
const plan = "professional";
switch (plan) {
case "starter":
console.log("Starter plan selected");
break;
case "professional":
console.log("Professional plan selected");
break;
case "organization":
console.log("Organization plan selected");
break;
default:
console.log("Unknown plan");
}
Explanation
switch checks the value of plan.
If plan is "professional", that case runs.
break stops the switch.
Diagram 27. Which branching tool to choose
if
→ one condition
if...else
→ two branches
else if
→ many different conditions
ternary
→ short two-result expression
switch
→ one value, many exact matches
Explanation
This is one of the most important practical rules in this topic.
28. Quick reminder
ifis universalif...elseis good for two brancheselse ifis good for many conditions- ternary is good for short two-result code
switchis good for many exact values
Also remember:
- ternary must have exactly two outcomes
switchcompares with strict equalitydefaultshould be lastbreakis usually needed
29. Block scope
Now let’s connect branching with scope.
A block with curly braces {} creates its own block scope.
This includes:
ifelse- loops
- functions
Variables declared inside that block are local to that block.
Diagram 28. Block scope idea
Outside block → global scope
Inside { }
→ local block scope
Explanation
A variable declared inside an if block exists only inside that block.
30. Global scope example
const value = "I'm a global variable";
if (true) {
console.log(value); // "I'm a global variable"
}
console.log(value); // "I'm a global variable"
Diagram 29. Global variable visibility
const value = "I'm a global variable"
Can be used:
- inside if block
- outside if block
Explanation
Because the variable is declared outside the block, it is global.
31. Local block scope example
if (true) {
const value = "I'm a local variable";
console.log(value); // "I'm a local variable"
}
console.log(value); // ReferenceError
Diagram 30. Local variable visibility
if (true) {
const value = "I'm a local variable";
}
Inside block:
value exists
Outside block:
value does not exist
Explanation
A variable declared inside the if block stays inside that block.
32. Nested scope
Scopes can be nested.
A scope has access to:
- its own variables
- variables from outer scopes
A scope does not have access to variables from inner nested scopes that belong to other blocks.
Example
const globalVar = "Global";
console.log(globalVar);
if (true) {
const aVar = "A";
console.log(globalVar);
console.log(aVar);
if (true) {
const bVar = "B";
console.log(globalVar);
console.log(aVar);
console.log(bVar);
}
}
if (true) {
const cVar = "C";
console.log(globalVar);
console.log(cVar);
}
Diagram 31. Nested scopes
Global
│
├─ A
│ └─ B
│
└─ C
Explanation
Think of this like a tree of scopes.
Globalis the outer scopeAis insideGlobalBis insideACis also insideGlobal
33. Access rules in nested scopes
Access summary
Globalcan use only global variablesAcan use variables fromAandGlobalBcan use variables fromB,A, andGlobalCcan use variables fromCandGlobal
But:
Acannot use variables fromBAcannot use variables fromCBcannot use variables fromCCcannot use variables fromAorB
Diagram 32. Scope access rules
B can look upward:
B → A → Global
B cannot look sideways:
B ✗ C
A cannot look downward into B unless code is inside B
C cannot look into A or B
Explanation
A block can look outward to its parent scopes, but not into separate inner blocks.
34. Common beginner mistakes
Mistake 1. Using if when you need if...else
let result = "";
if (score >= 50) {
result = "Pass";
}
If score < 50, nothing is assigned. Sometimes you need else too.
Mistake 2. Wrong condition in stock task
Bad logic:
if (available <= ordered)
This incorrectly rejects equal values like 80, 80.
Correct logic:
if (ordered > available)
Mistake 3. Returning the string "undefined"
Wrong:
return "undefined";
Correct idea:
- return nothing
- then JavaScript returns real
undefined
Mistake 4. Forgetting break in switch
This may accidentally run extra cases.
Diagram 33. Common branching mistakes
1. Missing else when two branches are needed
2. Wrong condition in comparison
3. Confusing undefined with "undefined"
4. Forgetting break in switch
Explanation
These are very common beginner errors, so it is good to watch for them early.
35. Full summary
Main branching tools
if
Runs code only if a condition is true.
if...else
Chooses between two branches.
else if
Checks several conditions in order and stops at the first true one.
Ternary operator
Short form of if...else for simple two-result expressions.
switch
Compares one value with many exact possible values.
break
Stops switch after a case is executed.
default
Runs if no case matches.
Block scope
Variables declared inside {} are visible only inside that block.
Diagram 34. Final map of branching
Branching
│
├─ if
├─ if...else
├─ else if
├─ ternary operator
├─ switch
│ ├─ case
│ ├─ break
│ └─ default
└─ block scope
Explanation
This is the complete picture of the branching topic.
36. Quick revision block
1. Branching means choosing different code paths
2. if runs code only when condition is true
3. if...else chooses between two branches
4. else if checks many conditions in order
5. JavaScript stops at the first true else-if condition
6. Ternary operator is a short form for two outcomes
7. switch compares one value with many exact values
8. switch uses strict equality
9. break stops further case execution
10. default runs when no case matches
11. Curly braces create block scope
12. Variables inside a block are local to that block
37. Final conclusion
Branching is one of the foundations of JavaScript.
If you understand:
- how
ifworks - how
if...elseworks - how
else ifworks - when to use ternary
- when to use
switch - how
breakworks - how block scope works
then you already have a strong base for writing real interactive programs.
Branching is used everywhere in full stack development:
- in form validation
- in UI behavior
- in login systems
- in shopping carts
- in backend checks
- in API logic